package org.piax.dtngw;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
 
public class USBSend2Service extends Service implements Runnable {
 
    ServerSocket server;
    Socket socket;
    int port = 8080;    //�ｽﾊ信�ｽ|�ｽ[�ｽg:8080
    volatile Thread runner = null;
    private static List<Thread> threads = new ArrayList<Thread>();
 
    @Override
    public IBinder onBind(Intent intent) {
        return null; 
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        if (runner == null) {
            runner = new Thread(this);
            runner.start();
        }
        Log.d("test", "test");
        Toast.makeText(this, "USBSend2Service Start", Toast.LENGTH_SHORT).show();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "USBSend2Service Stop", Toast.LENGTH_SHORT).show();
    }
     
    public void run() {
        Thread thread = Thread.currentThread();
        try {
            server = new ServerSocket(port);
            while (thread == runner) {
                try {
                    socket = server.accept();
                    for (int i = 0; i < threads.size(); i++) {
                        Thread t = threads.get(i);
                        if (!t.isAlive()) {
                            threads.remove(i);
                        }
                    }
                    Thread t = new Thread(new RecvData(socket, getApplicationContext()));
                    threads.add(t);
                    t.start();
                } catch (IOException e) {
 
                }
            }
        } catch (IOException e) {
            Log.d("USBSend2Service", "ServerSocket IOException:" + e.getMessage());
        } finally {
            try {
                server.close();
                Log.d("USBSend2Service", "ServerSocket.close()");
            } catch (IOException e) {
                Log.d("USBSend2Service", "ServerSocket.close() IOException:" + e.getMessage());
            }
        }
        Log.d("USBSend2Service", "Recv");
    }
}